package t.yatush.core_infra_svc;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

public class SchemaBuilder {

	private static final String SQL_DIR = "target/classes/db/sql";

	private static SchemaBuilder instance;

	public static SchemaBuilder getInstance(){
		if(instance == null){
			instance = new SchemaBuilder();
		}
		return instance;
	}

	private ScriptEngine scriptEngine;
	private ScriptHistoryRetriever historyRetriever;

	private SchemaBuilder() {
		scriptEngine = ScriptEngine.getInstance();
		historyRetriever = ScriptHistoryRetriever.getInstance();
	}

	public void build() throws Exception{
		Set<String> scriptsHistory = historyRetriever.getScriptsHistory();
		if(scriptsHistory == null){
			// schema was never run before
			historyRetriever.createScriptDocTable();
			scriptsHistory = Collections.emptySet();
		}
		runScripts(scriptsHistory);
	}

	private void runScripts(Set<String> scriptsHistory) throws Exception {
		List<String> newScriptsHistory = new ArrayList<String>();
		File scriptsDir = new File(SQL_DIR);
		File[] files = scriptsDir.listFiles();
		for(File file : files){
			String fileName = file.getName();
			if (fileName.endsWith(".sql")){
				if(!scriptsHistory.contains(fileName)){
					try {
						scriptEngine.runFileScript(SQL_DIR+File.separator+fileName);
						newScriptsHistory.add(fileName);
					} catch (Exception e) {
						System.err.println("Failed to run script: "+fileName);
						e.printStackTrace();
					}
				}
			}
		}
		historyRetriever.insertHistoryChanges(newScriptsHistory);
	}


	public static void main(String[] args) {
		try {
			SchemaBuilder.getInstance().build();
		} catch (Exception e) {
			System.err.println("Problem!!");
			e.printStackTrace();
		}
	}



}
